<?php

namespace app\common\core;

use think\exception\HttpException;
use think\facade\Event;

class AddonRoute
{
    public function execute($addons,$module,$controller,$action)
    {
        $request = \request();
        $convert = true;
        $filter = $convert ? 'strtolower' : 'trim';
        $addons = $addons ? trim(call_user_func($filter, $addons)) : '';
        $module = $module ? trim(call_user_func($filter, $module)) : 'index';
        $controller = $controller ? trim(call_user_func($filter, $controller)) : 'index';
        $action = $action ? trim(call_user_func($filter, $action)) : 'index';
        Event::trigger('addon_begin', $request);
        if (! empty($addons) && !empty($module) && ! empty($controller) && ! empty($action)) {
            $info = get_addons_info($addons);
            if (! $info) {
                throw new HttpException(404, __('addon %s not found', $addons));
            }
            if (! $info['state']) {
                throw new HttpException(500, __('addon %s is disabled', $addons));
            }
            // 设置当前请求的控制器、操作
            $request->setController($controller)->setAction($action);
            // 监听addon_module_init
            Event::trigger('addon_module_init', $request);
            list($bol,$class) = get_addon_class($addons, 'controller',$module, $controller);
            if (! $bol) {
                throw new HttpException(404, __($class));
            }
//            echo '<pre>';
//            print_r($class);
//            exit;
            $instance = new $class(app());
            $vars = [];
            if (is_callable([$instance, $action])) {
                // 执行操作方法
                $call = [$instance, $action];
            } elseif (is_callable([$instance, '_empty'])) {
                // 空操作
                $call = [$instance, '_empty'];
                $vars = [$action];
            } else {
                // 操作不存在
                throw new HttpException(404,
                    __('addon action %s not found', get_class($instance).'->'.$action.'()'));
            }
            Event::trigger('addon_action_begin', $call);

            return call_user_func_array($call, $vars);
        }else{
            abort(500, lang('addon can not be empty'));
        }
//        exit;
    }
}